﻿using System;
using System.Collections.Generic;
using System.Text;
using Weibo2Sfdc.SfWeb;
using System.Windows.Forms;

namespace Weibo2Sfdc
{
    public class SyncEngine
    {
        private static SyncEngine _instance;
        private Client _client = new Client();
        public Client Client
        {
            get
            {
                return _client;
            }
            set
            {
                _client = Client.Util.getInstance();
            }
        }

        public DataCenter DataCenter
        {
            get
            {
                return DataCenter.GetInstance();
            }
            set
            {
            }
        }

        public static SyncEngine GetInstance()
        {
            if (_instance == null)
            {
                _instance = new SyncEngine();
            }
            return _instance;
        }

        public SyncEngine()
        {
            // check sfdc login
            String sfdc_usr = Properties.Settings.Default.SfdcUsername;
            String sfdc_pwd = Properties.Settings.Default.SfdcPassword;

            if (String.IsNullOrEmpty(sfdc_usr) || String.IsNullOrEmpty(sfdc_pwd))
            {
                MessageBox.Show("同步失败.\nSalesforce 账号或密码为空!");
                UserConfigForm usrConfig = new UserConfigForm();
                usrConfig.StartPosition = FormStartPosition.CenterParent;
                usrConfig.SelectTab("SfdcUserConfig");
                usrConfig.ShowDialog();
            }
            else
            {
                Client.UserName = sfdc_usr;
                Client.Password = sfdc_pwd;
            }

        }

        public void StartSync()
        {
            List<WBContentBean> beans = DataCenter.Beans;
            if (!Client.isConnected())
            {
                Client.login();
            }
            List<TRIXPRO_WB__WBContent__c> contents = new List<TRIXPRO_WB__WBContent__c>();
            foreach (WBContentBean b in beans)
            {
                TRIXPRO_WB__WBContent__c wbc = new TRIXPRO_WB__WBContent__c();
                //创建时间
                wbc.TRIXPRO_WB__created_at__c = b.item_date;
                //微博信息内容
                wbc.TRIXPRO_WB__text__c = b.content;
                //微博ID
                wbc.TRIXPRO_WB__mid__c = b.mid;
                //微博作者uid
                wbc.TRIXPRO_WB__uid__c = b.uid;
                //微博作者
                wbc.TRIXPRO_WB__user__c = b.name;
                //来自
                wbc.TRIXPRO_WB__source__c = b.from;

                //keyword关键字ID
                wbc.TRIXPRO_WB__Keyword__c = b.kwc.Id;
                wbc.TRIXPRO_WB__Keyword_Category__c = b.kwc.TRIXPRO_WB__Keyword_Category__c;

                contents.Add(wbc);
            }
            SaveResult [] sr = Client.create(contents.ToArray());
        
        }
               

    }
}
